package com.jn.server;


import javax.swing.*;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintStream;
import java.net.Socket;

/**
 * @author 江南大学1033190417
 * @date 2022/4/7 19:52
 */
public class ConnectionThread extends Thread {
    public Socket client;//连接Web浏览器的socket字
    public int counter;//计数器
    public String path;
    public JTextArea lianjie;
    public JLabel fasong;
    public JLabel shoudao;

    public ConnectionThread(Socket cl, int c, String path, JTextArea lianjie, JLabel fasong, JLabel shoudao) {
        this.client = cl;
        this.counter = c;
        this.path = path;
        this.lianjie = lianjie;
        this.fasong = fasong;
        this.shoudao = shoudao;
    }


    @Override
    public void run() {
        Result result = new Result();
        try {
            result.IP = client.getInetAddress().toString();//客户机IP地址
            result.port = client.getPort();//客户机端口号
            System.out.println(client.getReceiveBufferSize());
            PrintStream outstream = new PrintStream(client.getOutputStream());
            DataInputStream instream = new DataInputStream(client.getInputStream());
            //读取Web浏览器提交的请求信息
            String inline = instream.readLine();//GET /index.html HTTP/1.1
            String requestType = getRequestType(inline);
            if ("GET".equals(requestType)) {
                result.method = "GET";
                String fileName = path + getFileName(inline);//根据根目录和用户的请求映射文件
                result.file = fileName;
                File file = new File(fileName);
                if (file.exists()) {//文件存在
                    result.isExist = true;
                    outstream.println("HTTP/1.0 200OK");
                    outstream.println("mime_version: 1.0");
                    outstream.println("Content-Type: text/html;charset=utf-8");
                    int len = (int) file.length();//计算文件大小
                    result.length = len;
                    outstream.println("content_length: " + len);
                    sendFile(outstream, file);//发送文件
                    outstream.close();
                } else {//文件不存在
                    result.isExist = false;
                    String notfound = "<html><head><title> Not Found</title></head> <body><h1> Error404-File notfound </h1></body ></html> ";
                    outstream.println("HTTP/1.0 404 no found");
                    outstream.println("Content-Type: text/html;charset=utf-8");
                    outstream.println("Content_Length: " + notfound.length() + 2);
                    result.length = notfound.length() + 2;
                    outstream.println("");
                    outstream.println(notfound);
                    outstream.flush();
                    outstream.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            synchronized (ConnectionThread.class) {
                lianjie.append("\n异常1：\n" + e + "\n");
            }
        }
        synchronized (ConnectionThread.class) {
            lianjie.append(result + "\n");
            Integer num = Integer.valueOf(fasong.getText());
            Integer length = result.length;
            num += (length == null ? 0 : length);
            fasong.setText(num + "");
            shoudao.setText((Integer.parseInt(shoudao.getText()) + 1) + "");
        }
    }


    //获取要访问的文件名
    public static String getFileName(String s) {
        String f = s.substring(s.indexOf(" ") + 1);
        f = f.substring(0, f.indexOf(" "));
        try {
            if (f.charAt(0) == '/')
                f = f.substring(1);
        } catch (Exception e) {
            System.out.println("Exception：" + e);
        }

        if (f.equals("")) f = "index.html";

        return f;
    }

    /**
     * 拿到请求的方法
     *
     * @param inline GET /index.html HTTP/1.1
     * @return GET, POST, PUT, DELETE
     */
    public static String getRequestType(String inline) {
        try {
            return inline.substring(0, inline.indexOf(" "));
        } catch (Exception e) {
            return null;
        }
    }

    //把指定文件发送给Web浏览器
    void sendFile(PrintStream outs, File file) {
        try {
            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int len = (int) file.length();
            byte[] buf = new byte[len];
            in.readFully(buf);
            outs.write(buf, 0, len);
            outs.flush();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
